from fastapi import APIRouter, HTTPException, Query
from tortoise.exceptions import DoesNotExist
from tortoise.functions import Sum  # 从 tortoise.functions 导入 Sum
from pydantic import BaseModel
from typing import List
from datetime import datetime, timedelta

from models.user import User
from models.products import Product
from models.payment import OrderFake, OrderItemFake  # 导入订单相关模型

router = APIRouter(tags=["热门商品推荐"])


class ProductResponse(BaseModel):
    id: int
    name: str
    description: str | None
    price: float
    image_url: str
    video_url: str
    inventory: int
    sales: int
    is_active: bool
    is_hot: bool
    share_count: int
    created_time: datetime
    updated_time: datetime
    total_purchased: int  # 新增字段：总购买数量

    class Config:
        from_attributes = True


@router.get("/api/hot/{user_id}", response_model=List[ProductResponse])
async def get_hot_products(
    user_id: int,
    limit: int = Query(10, ge=1, le=50),  # 限制返回数量，1-50之间
    days: int = Query(30, ge=1),  # 统计最近多少天的订单，默认30天
    min_purchases: int = Query(1, ge=1)  # 最低购买量门槛，默认1
):
    """
    根据订单中商品的实际购买数量获取热门商品
    
    - 统计逻辑：只计算已支付订单中的商品购买量
    - 可通过参数调整统计范围和返回数量
    """
    try:
        # 验证用户存在性
        await User.get(id=user_id)
        
        # 计算时间范围（只统计最近days天的订单）
        start_date = datetime.now() - timedelta(days=days)
        
        # 关联查询：统计每个商品的总购买数量
        # 只统计已支付的有效订单
        hot_products = await Product.filter(
            is_active=True,  # 只考虑激活状态的商品
            order_items__order__status="paid",  # 只统计已支付订单
            order_items__order__paid_at__gte=start_date  # 只统计指定时间范围内的订单
        ).annotate(
            total_purchased=Sum("order_items__quantity")  # 计算总购买数量
        ).filter(
            total_purchased__gte=min_purchases  # 过滤掉购买量太少的商品
        ).order_by(
            "-total_purchased"  # 按总购买量降序排列，购买越多越靠前
        ).limit(
            limit  # 限制返回数量
        ).all()
        
        return hot_products

    except DoesNotExist:
        raise HTTPException(status_code=404, detail="用户不存在")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"服务器错误: {str(e)}")